package cn.gok.homework;

import java.util.Comparator;
import java.util.TreeSet;

class Student implements Comparable<Student>{
    private int sid;
    private String name;
    private int age;

    public Student(int sid, String name, int age) {
        this.sid = sid;
        this.name = name;
        this.age = age;
    }

    public int getSid() {
        return sid;
    }

    public void setSid(int sid) {
        this.sid = sid;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "sid=" + sid +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    @Override
    //第一种方法
    public int compareTo(Student o) {
        //实现自定义比较规则
        //返回负数，说明本对象排在前面。返回0，代表两个对象相等，元素被判定为重复，无法进入set中。
        //返回正数，说明本对象排在后面
        if (this.sid<o.sid){
            return -1;
        }else if (this.sid==o.sid){
            //三元运算符
           return this.age<o.age?-1:1;
        }
        return 1;
    }
}
//自定义比较器(第二种方法)
class MyStudent implements Comparator<Student> {

    @Override
    public int compare(Student o1, Student o2) {
        if (o1.getSid() < o2.getSid()){
            return -1;
        }else if (o1.getSid()==o2.getSid()){
            //三元运算符
            return o1.getAge()<o2.getAge()?-1:1;
        }
        return 1;
    }
}
public class 第二题 {
//    2 创建类 Student：  int sid(学号) String name(姓名) ,int age;
//    要求使用两种方法实现自定义比较规则： 先按学号排，如果学号重复，按年龄排。
//    并遍历输出结果
    public static void main(String[] args) {
        //第一种方法();
        第二张方法();
    }

    private static void 第二张方法() {
        TreeSet<Student> students = new TreeSet<>(new MyStudent());
        students.add(new Student(101,"giao",38));
        students.add(new Student(101,"giao",18));
        students.add(new Student(100,"giao",40));
        students.stream().forEach(System.out::println);
    }

    private static void 第一种方法() {
        TreeSet<Student> students = new TreeSet<>();
        students.add(new Student(101,"giao",38));
        students.add(new Student(101,"giao",18));
        students.add(new Student(100,"giao",40));
        students.stream().forEach(System.out::println);
    }
}
